import util from "./util.js";
import authLogin from "./autuLogin";
import {
	HEADER,
	TOKENNAME,
	HTTP_REQUEST_URL,
	TOKEN_ID
} from "../config";
/**
 * 发送请求
 */

export default function request(api, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER;
	let token = uni.getStorageSync(TOKEN_ID);
	// console.log(!noAuth && token == '')
	if (!noAuth && token == '') {
		// authLogin();
		// uni.navigateTo({
		// 	url:'/pages/login/login?type=2'
		// })
		return Promise.reject({
			msg: "未登录",
			noAuth: false
		})
	}
	if (token != '') {
		header[TOKENNAME] = 'Bearer ' + token
	}
	return new Promise((reslove, reject) => {
		wx.request({
			url: Url + api,
			method: method || 'GET',
			header: {
				'user-token': token
			},
			data: data || {},
			success: res => {
				// console.log(res)
				// console.log(Url + api)
				if (noVerify) reslove(res.data, res);
				else if (res.data.code == 1) reslove(res.data, res);
				else if (res.data.code == 0) reslove(res.data, res);
				else if (res.data.code == -201) {
					uni.showToast({
						title:res.data.msg,
						icon:'none'
					})
					console.log('当前用户未经登录');
					setTimeout(()=>{
						uni.reLaunch({
							url: '/pages/login/login'
						})
					},1000)
				}
				else if (res.data.status == 400) {
					let pages = getCurrentPages(); //获取所有页面栈实例列表
					let prevPage = pages[pages.length - 1]; //上一页页面实例
					getApp().globalData.Tips({
						title: res.data.msg,
						icon: 'none'
					})
					if (prevPage.$vm.skip_page == 1) {
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							})
						}, 500)
					} else if (prevPage.$vm.skip_page == 2) {
						reslove(res.data, res)
					}
				} else if (res.data.status == 402) reslove(res.data, res);
				else if (res.data.status == 401) {
					uni.removeStorageSync(TOKEN_ID);
					uni.reLaunch({
						url: '/pages/login/login',
					})
				} else{
					reslove(res.data, res);
				} 
			},
			fail: msg => {
				console.log(msg)
				reject('请求失败');
			}
		});
	})
}
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach(method => {
	request[method] = (api, data, opt) => request(api, method, data, opt || {});
});
